package com.leesche.zcsp.node.web.controller.web.v2.register;

import com.leesche.zcsp.node.app.v1.timer.PhoneCodeCacheTimer;
import com.leesche.zcsp.node.app.v1.timer.VaildPhone;
import com.leesche.zcsp.node.utils.security.QEncodeUtil;
import com.leesche.zcsp.node.utils.web.SessionManager;
import com.leesche.zcsp.node.utils.web.gernerator.TimeGreaterUilt;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.controller.template.UserTemplate;
import com.leesche.zcsp.node.web.model.PubCustomer;
import com.leesche.zcsp.node.web.model.SysUser;
import com.leesche.zcsp.node.web.service.SysModuleService;
import com.leesche.zcsp.node.web.service.SysUserService;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysModuleCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysUserCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.SysUserDto;
import com.leesche.zcsp.node.web.vo.Principal;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Jerry Chen
 * @version V1.0
 * @Title: RegisterController.java
 * @Description: TODO(用户注册控制器)
 * @date 2016年10月5日 下午10:05:14
 */
@Controller
@RequestMapping("/v2/register")
public class WebRegisterController {

    private final static Logger LOGGER = Logger
            .getLogger(WebRegisterController.class.getName());

    //private static final String REGISTER_VIEW = "web/userinfo/userinfo";
    private static final String PERFECT_VIEW = "web/userinfo/customerinfo";

    private static final String REGISTER_VIEW = "web/v2/register/register";

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysModuleService sysModuleService;

    @RequestMapping(value = "/gotoRegister", method = RequestMethod.GET)
    public String showUserInfoView() {
        return REGISTER_VIEW;
    }

    @RequestMapping(value = "/perfect", method = RequestMethod.GET)
    public String showCustomerInfoView() {
        return PERFECT_VIEW;
    }

    @ResponseBody
    @RequestMapping(value = "/submitUserInfo", method = RequestMethod.POST)
    public Map<String, Object> addUserInfo(SysUser sysUser, String factoryCode, String smscode, String imgcode) {
        try {

            if (!SessionManager.getSessionAttribute(Constants.LOGIN_CODE).equals(imgcode)) {
                return WebResult.failure("验证码输入错误").put("ERROR", "imgcode").toMap();
            } else if (smscode == null || "".equals(smscode)) {
                return WebResult.failure("短信验证码不能为空").put("ERROR", "smscode").toMap();
            } else if (factoryCode == null || "".equals(factoryCode)) {
                return WebResult.failure("工厂码不能为空").put("ERROR", "factorycode").toMap();
            } else {
                SysUser user = new SysUser();
                user.setUsername(sysUser.getUsername());
                user = sysUserService.findUserByUsername(user);
                if (user != null) {
                    return WebResult.failure("用户名已存在").put("ERROR", "username").toMap();
                }
            }

            VaildPhone validPhone = PhoneCodeCacheTimer.get(smscode);
            if (validPhone == null) {
                return WebResult.failure("短信验证码错误，请重新输入").put("ERROR", "smscode").toMap();
            } else if (validPhone.getValidTime() < new Date().getTime()) {
                PhoneCodeCacheTimer.remove(smscode);
                return WebResult.failure("短信验证码已过期，请重新获取").put("ERROR", "smscode").toMap();
            } else if (!validPhone.getPhone().equals(sysUser.getMobile())) {
                return WebResult.failure("与获取短信的手机号码一致").put("ERROR", "smscode").toMap();
            }

            QuerySysUserCondition condition = new QuerySysUserCondition();
            condition.setBusinessno(factoryCode);
            condition.setNtype(2);
            List<SysUserDto> userDto = sysUserService.findListsByCondition(condition);
            if (userDto == null || userDto.size() <= 0) {
                return WebResult.failure("工厂码不存在，请核对后再输入").put("ERROR", "factorycode").toMap();
            } else {
                PhoneCodeCacheTimer.remove(smscode);
            }

            // 所有商户的父级ID都是超级管理员
            sysUser.setPuserid(userDto.get(0).getUserid());
            sysUser.setAdminid(1L);
            // 所有商户的类型都是4
            sysUser.setNtype(4);
            // 所有商户的备注都是“商业用户”
            sysUser.setRemark("商业用户");
            // 所有商户的状态默认都是在用
            sysUser.setState(1);
            // 所有商户只要手机验证码通过，手机验证都是已验证
            sysUser.setMobileconfirmed(1);
            sysUser.setCreatetime(new Date());
            // 所有商户的有效期默认都是3年
            sysUser.setOuttime(TimeGreaterUilt.specifiedTime(Calendar.YEAR, 3));
            sysUser.setPassword(QEncodeUtil.md5Encrypt(sysUser.getPassword()));

            sysUser = sysUserService.addUserInfo(sysUser);
            if (sysUser != null) {
                //保存用户登录状态
                Integer loginType = Constants.MODULE_TYPE_WEB;
                QuerySysModuleCondition querySysModuleCondition = new QuerySysModuleCondition();
                querySysModuleCondition.setnType(loginType);
                querySysModuleCondition.setUserId(sysUser.getUserid());
                List<Long> userModules = sysModuleService.findModuleIDbyUserID(querySysModuleCondition);
                sysUserService.saveLoginState(sysUser, userModules, loginType);

                return WebResult.success().toMap();
            }
            return WebResult.failure("注册失败，请稍后重试").toMap();
        } catch (Exception e) {
            // TODO: handle exception
            LOGGER.error(e.getMessage(), e);
            e.printStackTrace();
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/submitCustomerInfo", method = RequestMethod.POST)
    public Map<String, Object> addCustomerInfo(final PubCustomer customer) {

        return null;
    }

    @ResponseBody
    @RequestMapping(value = "/changeCustomerInfo", method = RequestMethod.POST)
    public Map<String, Object> changeCustomerInfo(final PubCustomer customer) {

        return null;
    }

}
